﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CoreEx.Common.Extensions;
using LinFu.IoC.Configuration;
using CoreEx.DynamicInvoker;
namespace CoreEx.Common.Repository.Implementation
{
    [Implements(typeof(IPropertyValueExtractor))]
    public class  PropertyValueExtractor : IPropertyValueExtractor
    {
        
        private readonly IDictionary<Type,IList<PropertyInfo>> _properties 
            = new Dictionary<Type, IList<PropertyInfo>>();

        public IDictionary<string, object> GetPropertyValues(object target)
        {
            var type = target.GetType();

            if (!_properties.ContainsKey(type))            
                _properties.Add(type,GetProperties(type));

            IDictionary<string, object> values = new Dictionary<string, object>();
            foreach (var propertyInfo in _properties[type])
            {                
                values.Add(propertyInfo.Name, propertyInfo.DynamicInvoke(target));
            }

            return values;
        }

        protected virtual IList<PropertyInfo> GetProperties(Type type)
        {
            return type.GetProperties().Where(p => !p.PropertyType.IsEnumerable()).ToList();
        }

    }
}
